package com.zd.commodity.product_pic.dao.impl;

import java.io.File;
import java.sql.Timestamp;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.zd.commodity.dao.impl.BaseDao;
import com.zd.commodity.product_pic.dao.IProductPicDao;
import com.zd.commodity.product_pic.entity.ProductPic;
import com.zd.commodity.userMng.entity.User;

@Repository("productPicDao")
public class ProductPicDaoImpl extends BaseDao<ProductPic> implements IProductPicDao {

	@Resource(name = "sessionFactory")
	public void setSuperSessionFactory(SessionFactory sessionFactory){
		super.setSessionFactory(sessionFactory);
	}
	
	@Override
	public DetachedCriteria getDetachedCriteria(ProductPic t1,ProductPic t2,Object param){
		DetachedCriteria dc=DetachedCriteria.forClass(ProductPic.class);
		if(t1!=null){
			if(!"".equals(t1.getName())){
				System.out.println("name:"+t1.getName());
				dc.add(Restrictions.like("name", t1.getName(), MatchMode.ANYWHERE));
			}
		}
		dc.addOrder(Order.desc("creationTime"));
		return dc;
	}
	
	@Override
	public void add(ProductPic t) {	
		String path=t.getPath();
		
		String filename=path.substring(1,path.lastIndexOf("/"));
		//String name=path.substring(path.lastIndexOf("/")+1,path.lastIndexOf("."));
		String extname=path.substring(path.lastIndexOf(".")+1,path.length());
		
		Timestamp creationtime=new Timestamp(System.currentTimeMillis());
		User user=(User)ServletActionContext.getRequest().getSession().getAttribute("user");
		
		
		t.setPath(path);
		t.setFileName(filename);
		t.setExtension(extname);
		t.setCreationTime(creationtime);
		t.setCreator(user.getUsername());
		
		getHibernateTemplate().save(t);		
	}
	
	
	@Override
	public void update(ProductPic t) {
		String path=t.getPath();
		
		String filename=path.substring(1,path.lastIndexOf("/"));
		//String name=path.substring(path.lastIndexOf("/")+1,path.lastIndexOf("."));
		String extname=path.substring(path.lastIndexOf(".")+1,path.length());
		
		Timestamp updatetime=new Timestamp(System.currentTimeMillis());
		User user=(User)ServletActionContext.getRequest().getSession().getAttribute("user");
		
		t.setPath(path);
		t.setFileName(filename);
		t.setExtension(extname);
		t.setUpdateTime(updatetime);
		t.setUpdater(user.getUsername());
		getHibernateTemplate().update(t);
	}
	
}
